//go:build darwin
// +build darwin

package collector

import (
	"encoding/xml"
	"os/exec"
	"strconv"
	"strings"

	"sysinfo/internal/types"
)

// SystemProfilerDisplays 表示system_profiler SPDisplaysDataType的XML输出
type SystemProfilerDisplays struct {
	Displays []Display `xml:"array>dict"`
}

type Display struct {
	Items []DisplayItem `xml:"array>dict"`
}

type DisplayItem struct {
	Name         string `xml:"key>string"`
	ChipsetModel string `xml:"dict>key[.='sppci_model']>string"`
	VRAMTotal    string `xml:"dict>key[.='sppci_vram']>string"`
	Vendor       string `xml:"dict>key[.='sppci_vendor']>string"`
	DeviceID     string `xml:"dict>key[.='sppci_device_id']>string"`
	BusType      string `xml:"dict>key[.='sppci_bus']>string"`
}

// collectGPUPlatform 实现macOS特定的GPU数据收集
func collectGPUPlatform() []types.GPUInfo {
	gpus := make([]types.GPUInfo, 0)

	// 使用system_profiler获取详细的GPU信息
	cmd := exec.Command("system_profiler", "SPDisplaysDataType", "-xml")
	output, err := cmd.Output()
	if err != nil {
		return gpus
	}Fallback to text parsing
		return collectGPUsFromSystemProfilerText()
	}

	// 解析XML输出
	var displays SystemProfilerDisplays
	if err := xml.Unmarshal(output, &displays); err != nil {
		return collectGPUsFromSystemProfilerText()
	}

	index := 0
	for _, display := range displays.Displays {
		for _, item := range display.Items {
			gpuInfo := types.GPUInfo{
				Index: index,
			}

			// 解析芯片组型号
			if item.ChipsetModel != "" {
				gpuInfo.Name = item.ChipsetModel
			}

			// 确定厂商
			vendor := strings.ToLower(item.Vendor)
			if strings.Contains(vendor, "nvidia") {
				gpuInfo.Vendor = "NVIDIA"
			} else if strings.Contains(vendor, "amd") || strings.Contains(vendor, "ati") {
				gpuInfo.Vendor = "AMD"
			} else if strings.Contains(vendor, "intel") {
				gpuInfo.Vendor = "Intel"
			} else if strings.Contains(vendor, "apple") {
				gpuInfo.Vendor = "Apple"
			} else {
				gpuInfo.Vendor = item.Vendor
			}

			// 解析显存（格式："8 GB"或"8192 MB"）
			if item.VRAMTotal != "" {
				gpuInfo.MemoryTotal = parseVRAM(item.VRAMTotal)
				if gpuInfo.MemoryTotal > 0 {
					gpuInfo.MemoryFormatted = item.VRAMTotal
				}
			}

			// 设备ID作为UUID替代
			if item.DeviceID != "" {
				gpuInfo.UUID = item.DeviceID
			}

			// 尝试获取Apple Silicon的Metal信息
			if gpuInfo.Vendor == "Apple" {
				enrichAppleSiliconGPU(&gpuInfo)
			}

			gpus = append(gpus, gpuInfo)
			index++
		}
	}

	return gpus
}

// collectGPUsFromSystemProfilerText 作为回退方案解析文本输出
func collectGPUsFromSystemProfilerText() []types.GPUInfo {
	gpus := make([]types.GPUInfo, 0)

	cmd := exec.Command("system_profiler", "SPDisplaysDataType")
	output, err := cmd.Output()
	if err != nil {
		return gpus
	}

	lines := strings.Split(string(output), "\n")
	var currentGPU *types.GPUInfo
	index := 0

	for _, line := range lines {
		line = strings.TrimSpace(line)

		if strings.Contains(line, "Chipset Model:") {
			// 发现新的GPU
			if currentGPU != nil {
				gpus = append(gpus, *currentGPU)
			}
			currentGPU = &types.GPUInfo{
				Index: index,
			}
			index++

			parts := strings.SplitN(line, ":", 2)
			if len(parts) == 2 {
				currentGPU.Name = strings.TrimSpace(parts[1])

				// 从名称确定厂商
				nameLower := strings.ToLower(currentGPU.Name)
				if strings.Contains(nameLower, "nvidia") {
					currentGPU.Vendor = "NVIDIA"
				} else if strings.Contains(nameLower, "amd") || strings.Contains(nameLower, "radeon") {
					currentGPU.Vendor = "AMD"
				} else if strings.Contains(nameLower, "intel") {
					currentGPU.Vendor = "Intel"
				} else if strings.Contains(nameLower, "apple") {
					currentGPU.Vendor = "Apple"
				}
			}
		} else if currentGPU != nil {
			if strings.Contains(line, "VRAM") || strings.Contains(line, "Memory") {
				parts := strings.SplitN(line, ":", 2)
				if len(parts) == 2 {
					vramStr := strings.TrimSpace(parts[1])
					currentGPU.MemoryTotal = parseVRAM(vramStr)
					if currentGPU.MemoryTotal > 0 {
						currentGPU.MemoryFormatted = vramStr
					}
				}
			} else if strings.Contains(line, "Vendor:") {
				parts := strings.SplitN(line, ":", 2)
				if len(parts) == 2 && currentGPU.Vendor == "" {
					currentGPU.Vendor = strings.TrimSpace(parts[1])
				}
			}
		}
	}

	// Add last GPU
	if currentGPU != nil {
		gpus = append(gpus, *currentGPU)
	}

	return gpus
}

// enrichAppleSiliconGPU 添加Apple Silicon特定信息
func enrichAppleSiliconGPU(gpu *types.GPUInfo) {
	// 对于Apple Silicon，我们可以尝试从Metal获取更多信息
	// 这需要额外的命令或API
	// 现在只设置驱动为Metal
	gpu.Driver = "Metal"
}

// parseVRAM 将VRAM字符串转换为字节
func parseVRAM(vramStr string) uint64 {
	vramStr = strings.TrimSpace(vramStr)
	vramStr = strings.ToUpper(vramStr)

	// 移除常见后缀以获取数字
	var multiplier uint64 = 1
	if strings.Contains(vramStr, "GB") {
		multiplier = 1024 * 1024 * 1024
		vramStr = strings.Replace(vramStr, "GB", "", -1)
	} else if strings.Contains(vramStr, "MB") {
		multiplier = 1024 * 1024
		vramStr = strings.Replace(vramStr, "MB", "", -1)
	}

	vramStr = strings.TrimSpace(vramStr)
	if val, err := strconv.ParseUint(vramStr, 10, 64); err == nil {
		return val * multiplier
	}

	return 0
}
